<template>
  <div>
    <el-upload
      list-type="picture-card"
      :limit="1"
      action="#"
      :on-preview="preview"
      :on-remove="handleRemove"
      :on-change="changeFile"
      :before-upload="beforeUpload"
      :file-list="fileList"
      :http-request="upload"
      :class="{ disabled:fileComputed}"
    >
      <!-- action是上传粉地址 -->
      <i class="el-icon-plus" />
    </el-upload>
    <el-progress v-if="showPercent" style="width: 180px" :percentage="percent" />
    <el-dialog title="图片预览" :visible.sync="showDialog">
      <img :src="imgUrl" style="width:100%" alt="">
    </el-dialog>
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5'
const cos = new COS({
  SecretId: 'AKID73j9IAl6AxTiheLlvoQlqeBQO7algKhn',
  SecretKey: 'qRloZ3HDxQdZEdnjPoyuaz7zZsuf9MIx'
})
export default {
  name: 'ImageUpload',
  data() {
    return {
      fileList: [], // 图片地址设置为数组
      showDialog: false,
      imgUrl: '',
      currentFileUid: '', // 用一个变量 记住当前上传的图片id
      showPercent: false,
      percent: 0
    }
  },
  computed: {
    // 判断是否上传了文件,显示与隐藏加号
    fileComputed() {
      return this.fileList.length === 1
    }
  },
  methods: {
    preview(file) {
      this.showDialog = true
      this.imgUrl = file.url
    },
    handleRemove(file, fileList) {
      // 删除图片
      this.fileList = fileList
    },
    changeFile(file, fileList) {
      // 上传成功和失败都是执行两次
      this.fileList = fileList.map(item => item)
    },
    // 点击上传之前的校验
    beforeUpload(file) {
      // 定义上传的文件格式
      const types = ['image/jpeg', 'image/gif', 'image/bmp', 'image/png']
      // 判断上传的格式是否存在
      if (!types.includes(file.type)) {
        this.$message.success('上传图片只能是 JPG、GIF、BMP、PNG 格式!')
        return false
      }
      // 检查上传文件抵消
      const maxSize = 5 * 1024 * 1024
      if (file.size > maxSize) {
        this.$message.success('图片大小最大不能超过5M')
        return false
      }
      this.currentFileUid = file.uid
      this.showPercent = true
      return true
    },
    upload(params) {
      if (params.file) {
        cos.putObject({
          Bucket: 'sun-1121-1307211947',
          Region: 'ap-nanjing',
          Key: params.file.name,
          Body: params.file, // 文件对象
          StorageClass: 'STANDARD',
          onProgress: (params) => {
            // 进度条
            this.percent = params.percent * 100
          }
        }, (err, data) => {
          console.log(err || data)
          if (!err && data.statusCode === 200) {
            // 说明上传成功
            this.fileList = this.fileList.map(item => {
              if (item.pid === this.currentFileUid) {
                return { url: 'http://' + data.Location, upload: true }
              }
              return item
            })
            setTimeout(() => {
              this.showPercent = false // 隐藏进度条
              this.percent = 0 // 进度归0
            }, 2000)
            // 将上传成功地地址会写到fileList里
          }
        })
      }
    }
  }
}
</script>

<style>
.disabled .el-upload--picture-card {
  display: none
}
</style>
